$(document).ready(function() {
	$("#limit, #sidx, #sord").msDropDown();
	
	$("input[name='compare']").click(function(){
		if ($("input[name='compare']:checked").length > 4){
			var error_message = '[compare_to_much_items]';
			if (lang.compare_to_much_items != undefined) {
				error_message = lang.compare_to_much_items;
			}
			alert(error_message);
			return false;
		}
	});
	
	$("#compare-btn, .compare-btn").click(function(){
		if ($("input[name='compare']:checked").length < 1){
			var error_message = '[compare_no_items]';
			if (lang.compare_no_items != undefined) {
				error_message = lang.compare_no_items;
			}
			alert(error_message);
			return false;
		}
		var search_ids = '';
		$("input[name='compare']:checked").each(function(i,el){
			search_ids += $(el).val() + ",";
		});
		search_ids = search_ids.substring(0,search_ids.length-1);

		window.location = settings.base_url + lang.lang_key + '/compare/compare_items/' + search_ids;
	});
	
	$("#limit").change(function(){
		$.ajax({
			url: settings.base_url + lang.lang_key + '/product_list/get_url',
			dataType: 'json',
			type: 'POST',
			data:{
				value: function() {return $('#limit').val()},
				current_url: function(){return $("#current_url").val()},
				type: 'per_page'
			},
			success: function(data){
				if (data.status){
					window.location = data.url;
				}
			},
		});
	});
	
	$("#sidx").change(function(){
		$.ajax({
			url: settings.base_url + lang.lang_key + '/product_list/get_url',
			dataType: 'json',
			type: 'POST',
			data:{
				value: function() {return $('#sidx').val()},
				current_url: function(){return $("#current_url").val()},
				type: 'order_by'
			},
			success: function(data){
				if (data.status){
					window.location = data.url;
				}
			},
		});
	});
	
	$("#sord").change(function(){
		 $.ajax({
            url: settings.base_url + lang.lang_key + '/product_list/get_url',
            dataType: 'json',
            type: 'POST',
            data:{
            	value: function() {return $('#sord').val()},
            	current_url: function(){return $("#current_url").val()},
            	type: 'order_dir'
            },
            success: function(data){
                if (data.status){
                    window.location = data.url;
                }
            },
        });
	});
	
	if ($("#paginator a").length){
		$("#paginator a").each(function(i,el){
			$(el).bind('click',function(){
					getPage(el)
				});
		});
	}
});

function getPage(element){
	var url = $(element).attr('href');
	var current_url = $("#current_url").val();
	
	var lastPos = url.lastIndexOf('/');
	var number = url.substring(lastPos + 1);
	
	if (number.length == 0){
		number = 0;
	}
	
	current_url = current_url.replace(/\/[0-9]+\//,"/" + number + "/" );
	
	$(element).attr('href',current_url);
	
}